﻿using ConfExpert.Forms.Base;
using DevTeam;
using System.Data;
using System.Windows.Forms;

namespace ConfExpert.Forms.Araclar
{
    public partial class Consolidate2 : XForm
    {
        public Consolidate2()
        {
            InitializeComponent();
        }

        private void Consolidate2_Load(object sender, System.EventArgs e)
        {
            ds.Clear();
            if (openFileDialog1.ShowDialog() == DialogResult.OK)
                if (openFileDialog1.OpenFile() != null)
                {
                    DataTable dt = ReadExcel(openFileDialog1.FileName);
                    if (dt == null)
                        return;

                    gridView1.Init(dt);
                    gridView1.BestFitColumns();


                    //string FilePath = Dialogs.SaveFile("Excel Document", "Excel Documents|*.xlsx");
                    //XlsxExportOptions opt = new XlsxExportOptions();
                    //opt.TextExportMode = TextExportMode.Value;

                    //gridView1.ExportToXlsx(FilePath, opt);

                    //System.Diagnostics.Process process = new System.Diagnostics.Process();
                    //process.StartInfo.FileName = FilePath;
                    //process.Start();

                }
        }

        public DataTable ReadExcel(string filename)
        {
            SpreadsheetGear.IWorkbook workbook = SpreadsheetGear.Factory.GetWorkbook(filename);
            System.Data.DataSet dataSet = workbook.GetDataSet(SpreadsheetGear.Data.GetDataFlags.NoColumnHeaders);

            bool firstrow = false;
            foreach (DataTable d in dataSet.Tables)
            {
                if (d.TableName.StartsWith("Sheet"))
                    continue;

                d.Columns.Add("SheetName", typeof(string));

                foreach (DataRow r in d.Rows)
                    r["SheetName"] = d.TableName;

                for (int i = d.Rows.Count - 1; i >= 0; i--)
                    if (!(d.Rows[i][0].ToStr() == "Row" && !firstrow) &&
                        d.Rows[i][0].ToInt() == 0)
                        d.Rows.RemoveAt(i);

                firstrow = true;
                dataSet.Tables[0].Merge(d);
            }

            return dataSet.Tables[0];

        }
    }
}
